In this recipe we look at how a very short piece of JavaScript code can clean up HTML menus and selection drop-downs.
Discussion
This two-line script crams a lot of work into a tiny space. The author, Air Force Staff Sgt. Mark Cartwright, has the following to say about it:'What it is is a pull-down menu for navigation purposes. Instead of checking the value of each field and setting the result, it can read the value no matter how many fields you have.
This is a piece of code that I have seen done elsewhere, but I have re-done it to make it more manageable from the maintenance point of view, and to improve loading time [with] a lesser amount of code.'
For demonstration purposes we've replaced the page-changing aspect with an alert message, but here's what the function looks like as you'd actually use it:
function menuSelect(theform) { var page = theform.pageSelect.options[theform.pageSelect.selectedIndex].value; parent.location.href=page; }The truly interesting part is that, because the form is passed to the function (and provided you always name the selection object 'pageSelect'), this code can service several pages in a suite by caching it in an invisible frame.
The following drop-down adds another wrinkle--you can use the onChange() event to trigger a call to the JavaScript function, so you don't even need the "Go!" button in the previous menu.
Copyright ©2000 by Charles River Media, All Rights Reserved